package com.ruge.test.Velocity;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.tools.generic.DateTool;
import org.junit.Test;

import java.io.*;
import java.util.Date;

/**
 * 爱丽丝、如歌  创建于 2018/7/10 20:29
 * 说明:  TODO
 */
public class Velociry_06_outputFile {
    @Test
    public void test1() throws IOException {

        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();

        VelocityContext context = new VelocityContext();
        context.put("title", "测试标题");
        context.put("body", "测试内容");
        String str = "velocity/Velocity_06_outputFile.vm";
        Template template = velocityEngine.getTemplate(str);

        File saveFile = new File("F:test.html");
        //创建文件输出流
        FileOutputStream outStream = new FileOutputStream(saveFile);
        //因为模板整合的时候，需要提供一个Writer，所以创建一个Writer
        OutputStreamWriter writer = new OutputStreamWriter(outStream);
        //创建一个缓冲流
        BufferedWriter bufferWriter = new BufferedWriter(writer);

        template.merge(context, bufferWriter);
        //强制刷新
        bufferWriter.flush();//强制刷新
        outStream.close();
        bufferWriter.close();
    }
}
